package com.example.demo2.interceptor;

import com.example.demo2.config.MapConfig;
import io.micrometer.observation.annotation.Observed;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.ConcurrentHashMap;


public class loginInterceptor implements HandlerInterceptor {

    private ConcurrentHashMap<String, Integer> concurrentMap;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        String url = request.getRequestURL().toString();
        if (url.contains("/login")||url.contains("/VistorLogin")||url.contains("/deletelogin")) {
            return true; // 登录请求放行
        }
        // 获取WebApplicationContext
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        // 通过context获取Bean
        concurrentMap = context.getBean(MapConfig.class).concurrentMap();
        // 检查用户是否已登录
        Object user = concurrentMap.get("uID");
        System.out.println("拦截器中的uID"+user);
        if (user == null) {
            System.out.println("没登录");
            response.sendRedirect("/login"); // 未登录用户重定向到登录页面
            return false;
        }

        return true; // 已登录用户放行
    }
}

